package com.cch.stock.report.bean;

import java.util.Calendar;
import java.util.Date;

import com.cch.platform.util.DateUtil;

public class QueryTime {
	
	public enum Period {
		day,week,month,quarter,year
	}
	
	private Period period;
	
	private Date beginDay;
	
	private Date endDay;
	
	private Calendar iter;
	
	
	public Period getPeriod() {
		return period;
	}

	public void setPeriod(Period period) {
		this.period = period;
	}

	public Date getBeginDay() {
		return beginDay;
	}

	public void setBeginDay(Date beginDay) {
		if(beginDay!=null){
			beginDay=DateUtil.floorTime(beginDay);
		}
		this.beginDay = beginDay;
	}

	public Date getEndDay() {
		return endDay;
	}

	public void setEndDay(Date endDay) {
		if(endDay!=null){
			endDay=DateUtil.ceilTime(endDay);
		}
		this.endDay=endDay;
	}
	
	public Date getNextDay() {
		if (iter == null) {
			this.initIter();
		}
		if(iter.getTime().compareTo(endDay)>=0){
			return null;
		}
		switch (this.period) {
		case week:
			iter.add(Calendar.DATE, 7);
			break;
		case month:
			iter.add(Calendar.MONTH, 1);
			break;
		case quarter:
			iter.add(Calendar.MONTH, 3);
			break;
		case year:
			iter.add(Calendar.YEAR, 1);
			break;
		default:
			iter.add(Calendar.DATE, 1);
			while(!DateUtil.isOpen(iter)){
				iter.add(Calendar.DATE, 1);
			}
			break;
		}
		if(iter.getTime().compareTo(endDay)>0){
			return endDay;
		}
		return iter.getTime();
	}
	
	private void initIter() {
		iter = Calendar.getInstance();
		iter.setTime(beginDay);
		switch (this.period) {
		case day:
			iter.add(Calendar.DATE, -1);
			break;
		case week:
			iter.set(Calendar.DAY_OF_WEEK, 1);
			break;
		case month:
			iter.set(Calendar.DAY_OF_MONTH, 1);
			break;
		case quarter:
			iter.set(Calendar.DAY_OF_MONTH, 1);
			int i = iter.get(Calendar.MONTH) / 3 * 3;
			iter.set(Calendar.MONTH, i);
			break;
		case year:
			iter.set(Calendar.DAY_OF_YEAR, 1);
			break;
		default:
			break;
		}
		iter.set(Calendar.HOUR_OF_DAY, 23);
		iter.set(Calendar.SECOND,59);
		iter.set(Calendar.MINUTE,59);
		iter.set(Calendar.MILLISECOND,999);
	}
}
